//
//  MainViewController.swift
//  AIImage
//
//  Created by deng on 2023/12/10.
//

import UIKit
import ZLPhotoBrowser
import Alamofire
import HandyJSON
import CommonCrypto
import Toast_Swift

class MainViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    lazy var settingButton:UIButton = {
        let btn:UIButton = UIButton.init()
        btn.setImage(UIImage(named: "setting"), for: .normal)
        return btn
    }()
    
    lazy var tableView:UITableView = {
        let tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        return tableView
    }()
    
    var dataList = LocalMan.shared.getAIModelList()
    var titleStr = "AI物体识别"
    let bgView = UIImageView.init(image: UIImage(named: "bg_icon"))
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if #available(iOS 15.0, *) {
            let barAppearance = UINavigationBarAppearance.init()
            barAppearance.backgroundColor = .clear
            navigationController?.navigationBar.scrollEdgeAppearance = nil
            navigationController?.navigationBar.standardAppearance = barAppearance
        } else {
            navigationController?.navigationBar.barTintColor = .clear
            navigationController?.navigationBar.shadowImage = UIImage()
            navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        }
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.tintColor = .clear
        
        dataList = LocalMan.shared.getAIModelList()
        tableView.reloadData()
    }
    
    typealias StringBlock = (_ value : String) -> Void
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        initUI()
    }
    
    private func initUI(){
        
        bgView.frame = view.bounds
        bgView.isUserInteractionEnabled = true
        bgView.contentMode = .scaleAspectFill
        view.addSubview(bgView)
//        let tap1 = UITapGestureRecognizer(target: self, action: #selector(bgViewClick))
//        bgView.addGestureRecognizer(tap1)
        
        settingButton.setImage(UIImage(named: "setting"), for: .normal)
        settingButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: settingButton)
        settingButton.addTarget(self, action: #selector(settingClick), for: .touchUpInside)
        
        view.addSubview(tableView)
        tableView.frame = CGRect(x: 0, y: 120*DS.s, width: KScreenWidth, height: KScreenHeight-120*DS.s)
        tableView.register(cellType: MainHomeTableViewCell.self)
        tableView.register(cellType: MainHomeTitleTableViewCell.self)
        tableView.register(cellType: MainHistoryTableViewCell.self)
        
        getHomeData()
    }

    @objc func settingClick(){
        

        
        let setVc = SettingViewController()
        navigationController?.pushViewController(setVc, animated: true)
    }
    
    //delegete
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if dataList.count == 0{
            return 1
        }
        return 2+dataList.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell: MainHomeTableViewCell = tableView.dequeueReusableCell(for: indexPath)
            cell.titleL.text = self.titleStr
            cell.callBackBlock {[weak self] btnTag in
                self?.clickMenu(index: btnTag)
            }
            return cell
        }else if indexPath.row == 1{
            let cell:MainHomeTitleTableViewCell = tableView.dequeueReusableCell(for: indexPath)
            return cell
        }
        let cell:MainHistoryTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        let vo = dataList[indexPath.row-2]
        cell.historyImg.image = LocalMan.shared.getImage(imagePath: vo.imagePath ?? "")
        cell.nameLabel.text = vo.name ?? ""
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row >= 2{
            
            let vo = dataList[indexPath.row-2]
            let detailVC = AIDetailViewController.init()
            detailVC.detailVo = vo
            navigationController?.pushViewController(detailVC, animated: true)
        }
    }
    
    private func clickMenu(index:Int){
        
        let config = ZLPhotoConfiguration.default()
        config.allowSelectImage = true
        config.allowSelectVideo = false
        config.allowSelectGif = false
        config.allowSelectOriginal = false
        config.cropVideoAfterSelectThumbnail = true
        config.allowMixSelect = false
        config.maxSelectCount = 1
        
        let photoPicker = ZLPhotoPreviewSheet()
        photoPicker.selectImageBlock = { images, origin in
            
            let imageVo = images.first
            let image = imageVo?.image ?? UIImage()
            self.uploadImage(index: index, image: image)
        }
        photoPicker.showPhotoLibrary(sender: self)
    }
    
    private func uploadImage(index:Int,image:UIImage){
        let loadingView = LoadingView(frame: CGRect(x: KScreenWidth/2-70*DS.s, y: KScreenHeight/2-50*DS.s, width: 140*DS.s, height: 100*DS.s), text: "AI分析图片中...")
        view.addSubview(loadingView)
        getBaiKeToken { value in
            if value != ""{

                var path = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=\(value)"
                if index == 2{
                    path = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=\(value)"
                }else if index == 3{
                    path = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=\(value)"
                }else if index == 4{
                    path = "https://aip.baidubce.com/rest/2.0/image-classify/v1/landmark?access_token=\(value)"
                }else if index == 5{
                    path = "https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient?access_token=\(value)"
                }else if index == 6{
                    path = "https://aip.baidubce.com/rest/2.0/image-classify/v1/redwine?access_token=\(value)"
                }else if index == 7{
                    path = "https://aip.baidubce.com/rest/2.0/image-classify/v1/currency?access_token=\(value)"
                }
                let header:HTTPHeaders = ["Content-Type": "application/x-www-form-urlencoded",
                                          "Accept": "application/json"]
                let imageData = image.resetImg(lenght: 1242, KB: 2024)
                let base64String = imageData.base64EncodedString()
                AF.upload(multipartFormData: { multipartFormData in
                    if let data = base64String.data(using: .utf8) {
                        multipartFormData.append(data, withName: "image")
                    }
                }, to: path,headers: header).responseJSON { response in
                    loadingView.stopLoading()
                    switch response.result {
                    case .success(let dict):
                        // 处理上传成功后的响应
                        print("上传成功: \(dict)")
                        if let dic = dict as? NSDictionary {
                            
                            var result = [ResultList]()
                            if let list = dic["result"] as? [[String:Any]]{
                                for jsonStr in list {
                                    let vo = ResultList.deserialize(from: jsonStr) ?? ResultList()
                                    result.append(vo)
                                }
                            }
                            let first = result.first
                            let vo = AISaveModel()
                            vo.imagePath =  LocalMan.shared.saveAD(image: image)
                            vo.result = result
                            vo.name = first?.name ?? ""
                            LocalMan.shared.addAIModel(model: vo)
                            
                            let vc = AIDetailViewController()
                            vc.detailVo = vo
                            self.navigationController?.pushViewController(vc, animated: true)
                        }
                        
                    case .failure(_):
                        self.view.makeToast("识别失败")
                    }
                }
            }else{
                self.view.makeToast("识别失败")
            }
        }
    }
    
    private func getHomeData(){
        
        let url = "https://code-img-small-hhjilteyfi.cn-shanghai.fcapp.run"
        AF.request(url, method: .get, parameters: nil, encoding:  URLEncoding.default, headers: nil).responseJSON { response in
            switch response.result {
            case let .success(json):
                if let err = response.error {
                } else {
                    let dict = json
                    if let dic = dict as? NSDictionary {
                        self.titleStr = dic["hello"] as? String ?? ""
                        self.tableView.reloadData()
                    }
                }
            case let .failure(errorD):
                print("报错:\(errorD)")
            }
        }
    }
    
    private func getBaiKeToken(block: @escaping StringBlock){
        
        let url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=GP5zTZhMSjCTNLoT7wcTjYu3&client_secret=8qqvvWFQecITFOae5E1cqWeZUf2CNMOY"
        let header:HTTPHeaders = ["Content-Type": "application/json",
                       "Accept": "application/json"]
        AF.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: header).responseJSON { response in
            switch response.result {
            case let .success(json):
                if let err = response.error {
                    block("")
                } else {
                    let dict = json
                    if let dic = dict as? NSDictionary {
                        let token = dic["access_token"] as? String ?? ""
                        block(token)
                    }
                }
            case let .failure(errorD):
                print("报错:\(errorD)")
                block("")
            }
        }
    }
}

